<?php


namespace app\common\model;


use think\Exception;
use think\Model;

class ZhunleUserAccount extends Model
{
    protected $table = 'wechat_backup_07_18_14_43_00.zhunle_user_account';

    /**
     * 获取账户信息
     * @param $uid
     * @return array|object
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAccountInfoAndCreate($uid)
    {
        $accountInfoModel = $this->where('uid', $uid)
            ->field('total_amount,withdraw_price,balance,status,uid,last_time')
            ->find();
        // 判断用户账户是否存在或开通
        if ($accountInfoModel == null || empty($accountInfoModel))
        {
            // 初始化账户
            $accountInfo = $this->createAccount($uid);
        } else
        {
            $accountInfo = $accountInfoModel->data;
        }

        return $accountInfo;
    }

    /**
     * 账户初始化创建
     * @param $uid
     * @return array
     * @throws Exception
     */
    protected function createAccount($uid)
    {
        $data = [
            'uid' => $uid,
            'status' => 1,
            'last_time' => 0,
            'withdraw_price' => '0.00',
            'balance' => '0.00',
            'total_amount' => '0.00',
            'create_time' => time()
        ];

        try
        {
            $this->save($data);
        }
        catch (Exception $e)
        {
            throw new Exception('服务异常', config('code.error'));
        }

        return $data;
    }

}
